# -*- coding: utf-8 -*-
# filename: receive.py
import xml.etree.ElementTree as ET
from pydantic import BaseModel
from typing import Optional

def parse_xml(web_data):
    if len(web_data) == 0:
        return None
    xml_data = ET.fromstring(web_data)
    msg_type = xml_data.find('MsgType').text
    if msg_type == 'text':
        return TextMsg.from_xml(xml_data)
    elif msg_type == 'image':
        return ImageMsg.from_xml(xml_data)

class Msg(BaseModel):
    ToUserName: str
    FromUserName: str
    CreateTime: str
    MsgType: str
    MsgId: str

    @classmethod
    def from_xml(cls, xml_data):
        return cls(
            ToUserName=xml_data.find('ToUserName').text,
            FromUserName=xml_data.find('FromUserName').text,
            CreateTime=xml_data.find('CreateTime').text,
            MsgType=xml_data.find('MsgType').text,
            MsgId=xml_data.find('MsgId').text
        )

class TextMsg(Msg):
    Content: str

    @classmethod
    def from_xml(cls, xml_data):
        return cls(
            **Msg.from_xml(xml_data).__dict__,
            Content=xml_data.find('Content').text.encode("utf-8").decode("utf-8")
        )

class ImageMsg(Msg):
    PicUrl: str
    MediaId: str

    @classmethod
    def from_xml(cls, xml_data):
        return cls(
            **Msg.from_xml(xml_data).__dict__,
            PicUrl=xml_data.find('PicUrl').text,
            MediaId=xml_data.find('MediaId').text
        )